



import 'package:bt_tool/basic/bt_controller.dart';
import 'package:bt_tool/basic/bt_date_tool.dart';
import 'package:bt_tool/basic/bt_db_tool.dart';
import 'package:bt_tool/basic/bt_language_tool.dart';
import 'package:bt_tool/basic/bt_model.dart';
import 'package:bt_tool/basic/bt_notification_center.dart';
import 'package:bt_tool/basic/bt_router.dart';
import 'package:bt_tool/basic/bt_utils.dart';
import 'package:bt_tool/widget/bt_dialog_widget.dart';
import 'package:bt_tool/widget/bt_form_select_widget.dart';
import 'package:bt_tool/widget/bt_text_field.dart';
import 'package:bt_tool/widget/bt_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_demo/tools/donext/page/do_next_create_page.dart';
import 'package:flutter_demo/tools/donext/do_next_define.dart';
import 'package:flutter_demo/tools/donext/model/do_next_model.dart';
import 'package:flutter_demo/tools/project/project_define.dart';
import 'package:flutter_demo/tools/project/model/project_model.dart';
import 'package:flutter_demo/tools/project/project_tool.dart';
import 'package:flutter_demo/tools/translate/translate_tool.dart';
import 'package:get/get.dart';

import '../../../common/config/app_router.dart';


class DoNextMainController extends BTController{

  var dataList = <DoNextModel>[].obs;
  var selectProjectId = 0;
  var isCommandOrCtrl = false;
  var timeRangType = DoNextMainTimeType.today.obs;
  var projectSelectModelList = <BTFormSelectModel>[].obs;
  final Set<LogicalKeyboardKey> _keysPressed = {};


  @override
  Future<void> initState() async {
    super.initState();
    await BTDbTool.share().createTable(DoNextDefine.doNextTableName, [
      BTDbFieldModel("id",BTModelFieldType.intType,isPrimaryKey: true,isAutoIncrement: true),
      BTDbFieldModel("content",BTModelFieldType.stringType),
      BTDbFieldModel("startTime",BTModelFieldType.intType),
      BTDbFieldModel("createTime",BTModelFieldType.intType),
      BTDbFieldModel("status",BTModelFieldType.intType),
      BTDbFieldModel("endTime",BTModelFieldType.intType),
      BTDbFieldModel("isDel", BTModelFieldType.intType),
      BTDbFieldModel("pid", BTModelFieldType.intType,defaultValue: '0'),
    ]);
    projectSelectModelList.add(BTFormSelectModel(0, "全部", true));
    var projectModelList = await ProjectTool.getProjectData();
    for(var model in projectModelList){
      projectSelectModelList.add(BTFormSelectModel(model.id,model.name,false));
    }
    getData();
    BTNotificationCenter.share().add(DoNextDefine.doNextCreateSucNotify, this);
    BTNotificationCenter.share().add(DoNextDefine.doNextEditSucNotify, this);
    HardwareKeyboard.instance.addHandler((event){
      isCommandOrCtrl = event.logicalKey == LogicalKeyboardKey.metaLeft && event is KeyDownEvent;

      if(event is KeyUpEvent){
        _keysPressed.remove(event.logicalKey);
      }else if(event is KeyDownEvent){
        _keysPressed.add(event.logicalKey);
      }

      if(event is KeyDownEvent &&
          _keysPressed.contains(LogicalKeyboardKey.metaLeft) &&
          _keysPressed.contains(LogicalKeyboardKey.keyA) &&
          dataList.isNotEmpty){
        //全选或者反选
        if(dataList.first.isSelect){
          for(var m in dataList){
            m.isSelect = false;
          }
        }else{
          for(var m in dataList){
            m.isSelect = true;
          }
        }
        dataList.refresh();
      }



      return false;
    });
  }

  @override
  void btReceiveNotification(BTNotificationSendModel notificationModel) {
    super.btReceiveNotification(notificationModel);
    if(notificationModel.name == DoNextDefine.doNextCreateSucNotify || notificationModel.name == DoNextDefine.doNextEditSucNotify){
      getData();
    }
  }




  @override
  getData() async {
    String whereStr = "next.isDel != ?";
    List whereList = [1];
    if(timeRangType.value == DoNextMainTimeType.today){
      var dateStr = btDateFormatter(BTDateTool.YYYYMMDD, DateTime.now());
      var startDate = BTDateTool.convertStrTimeToDateTime("$dateStr 00:00:00");
      var endDate = BTDateTool.convertStrTimeToDateTime("$dateStr 23:59:59");
      whereStr = "$whereStr and next.startTime >= ? and next.endTime <= ?";
      whereList.add(BTDateTool.getSeconds(startDate));
      whereList.add(BTDateTool.getSeconds(endDate));
    }else if(timeRangType.value == DoNextMainTimeType.week){
      var map = BTDateTool.getThisWeekTimestamps();
      whereStr = "$whereStr and next.startTime >= ? and next.endTime <= ?";
      whereList.add(map["start"]);
      whereList.add(map["end"]);
    }

    if(selectProjectId != 0){
      whereStr = "$whereStr and next.pid == ?";
      whereList.add(selectProjectId);
    }
    String sql = "select next.*, p.name as projectName from ${DoNextDefine.doNextTableName} next left join ${ProjectDefine.tableName} p on next.pid = p.id where $whereStr order by next.createTime desc";
    var mapArray = await BTDbTool.share().rawQuery(sql,whereList);
    List<DoNextModel> modelList = [];
    for(var map in mapArray){
      modelList.add(DoNextModel(map));
    }
    dataList.clear();
    dataList.addAll(modelList);
  }

  create(BuildContext context){
    BTRouter.share().pushToUrl(routerUrl: AppRouterDefine.doNextCreatePage);
  }

  detClick(DoNextModel model) async {
    if(isCommandOrCtrl){
      model.isSelect = !model.isSelect;
      dataList.refresh();
      return;
    }
    BTRouter.share().pushToUrl(routerUrl: AppRouterDefine.doNextCreatePage,routerParameter: {
      "id" : model.id,
    });
  }

  showMenuView(DoNextModel model,Offset position) async {
    final overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
    List<PopupMenuItem> items = [
       PopupMenuItem<DoNextMainMenuAction>(value: DoNextMainMenuAction.copy, child: Text("复制内容".btTrans))
    ];
    if(model.status == DoNextStatus.ing.iValue){
      items.add(PopupMenuItem<DoNextMainMenuAction>(value: DoNextMainMenuAction.finish, child: Text("设置为已完成".btTrans)));
      items.add(PopupMenuItem<DoNextMainMenuAction>(value: DoNextMainMenuAction.addOneDay, child: Text("延后1天".btTrans)));
    }else if(model.status == DoNextStatus.finish.iValue){
      items.add(PopupMenuItem<DoNextMainMenuAction>(value: DoNextMainMenuAction.ing, child: Text("设置为进行中".btTrans)));
    }

    items.add(PopupMenuItem<DoNextMainMenuAction>(value: DoNextMainMenuAction.del, child: Text("删除数据".btTrans)));
    await showMenu(
    context: context,
    position: RelativeRect.fromRect(
      Rect.fromLTWH(position.dx, position.dy, 0, 0),
      Offset.zero & overlay.size,
    ),
    items: items,
    ).then((value) async {
      if (value == null) {
        return;
      }

      if (value == DoNextMainMenuAction.copy){
        Clipboard.setData(ClipboardData(text: model.content));
        BTToast.showToast("已复制".btTrans);
        return;
      }

      if (value == DoNextMainMenuAction.finish){
        model.status = DoNextStatus.finish.iValue;
        var map = model.convertToDictOnly(["status"]);
        await BTDbTool.share().update(DoNextDefine.doNextTableName, map,where: "id = ?",whereArgs: [model.id]);
        dataList.refresh();
        return;
      }

      if (value == DoNextMainMenuAction.ing){
        model.status = DoNextStatus.ing.iValue;
        var map = model.convertToDictOnly(["status"]);
        await BTDbTool.share().update(DoNextDefine.doNextTableName, map,where: "id = ?",whereArgs: [model.id]);
        dataList.refresh();
        return;
      }

      if (value == DoNextMainMenuAction.addOneDay){
        model.endTime += 3600 * 24;
        var map = model.convertToDictOnly(["endTime"]);
        await BTDbTool.share().update(DoNextDefine.doNextTableName, map,where: "id = ?",whereArgs: [model.id]);
        dataList.refresh();
        return;
      }

      if (value == DoNextMainMenuAction.del){
        model.isDel = 1;
        var map = model.convertToDictOnly(["isDel"]);
        await BTDbTool.share().update(DoNextDefine.doNextTableName, map,where: "id = ?",whereArgs: [model.id]);
        dataList.remove(model);
        return;
      }

    });
  }

  String getTimeStr(){
    if(timeRangType.value == DoNextMainTimeType.today){
      return "今天".btTrans;
    }

    if(timeRangType.value == DoNextMainTimeType.week){
      return "本周".btTrans;
    }

    if(timeRangType.value == DoNextMainTimeType.month){
      return "本月".btTrans;
    }


    return "全部".btTrans;
  }

  reportStyleClick(){
    List<DoNextGroupModel> groupModelList = [];
    for(var model in dataList){
      if(model.isSelect){
        DoNextGroupModel? existModel;
        for(var groupModel in groupModelList){
          if(groupModel.pid == model.pid){
            existModel = groupModel;
            break;
          }
        }
        if(existModel != null){
          existModel.title = "${existModel.title}\n${existModel.index}.${model.content}";
        }else{
          existModel = DoNextGroupModel(null);
          existModel.pid = model.pid;
          existModel.title = "${model.projectName}\n${existModel.index}.${model.content}";
          groupModelList.add(existModel);
        }
        existModel.index++;
      }
    }
    String dataStr = "";
    for(var m in groupModelList){
      if(dataStr.isEmpty){
        dataStr = m.title;
      }else{
        dataStr = "$dataStr\n\n${m.title}";
      }
    }
    if(dataStr.isEmpty){
      BTToast.showToast('按住Commend按键先选择任务'.btTrans);
      return;
    }
    String dialogKey = BTUtils.randomString();
    BTTextFieldController controller = BTTextFieldController(
      textEditingController: TextEditingController(text: dataStr)
    );
    BTAlertInputWidget inputWidget = BTAlertInputWidget(
      lineNum: 5,
      controller: controller,
      title: "编辑".btTrans,
      cancelStr: "取消".btTrans,
      okStr: "复制".btTrans,
      contentWidth: 450,
      clickCallBack: (action){
        BTDialog.dismiss(key: dialogKey);
        if(action == BTAlertAction.ok){
          Clipboard.setData(ClipboardData(text: controller.getText()));
          BTToast.showToast("已复制".btTrans);
        }
      },
    );
    BTDialog.show(inputWidget,key: dialogKey);
  }

}